package school.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import school.domain.School;
import school.util.DatabaseManager;

public class SchoolDAO {
	private static SchoolDAO instance = new SchoolDAO();
	private SqlSessionFactory factory;
	private SchoolDAO(){
		DatabaseManager manager = DatabaseManager.getInstance();
		factory = manager.getSqlSessionFactory();
	}
	public static SchoolDAO getInstance(){
		return instance;
	}
	
	//학교데이터 등록
	public int insertSchool(School school){
		SqlSession session = factory.openSession();
		try{
			int cnt = session.insert("school.insertSchool", school);
			session.commit();
			return cnt;
		}finally{
			session.close();
		}
	}
	//학교 데이터 수정
	public int updateSchool(School school){
		SqlSession session = factory.openSession();
		try{
			int cnt = session.update("school.updateSchool",school);
			session.commit();
			return cnt;
		}finally{
			session.close();
		}
	}
	//학교 ID로 학교정보 삭제
	public int deleteSchoolById(int schoolId){
		SqlSession session = factory.openSession();
		try{
			int cnt = session.delete("school.deleteSchoolById",schoolId);
			session.commit();
			return cnt;
		}finally{
			session.close();
		}
	}
	//학교 ID로 학교 조회
	public School selectSchoolById(int schoolId){
		SqlSession session = factory.openSession();
		try{
			School sch = session.selectOne("school.selectSchoolById",schoolId);
			return sch;
		}finally{
			session.close();
		}
	}
	//전체 학교 조회
	public List<School> selectSchoolList(){
		SqlSession session = factory.openSession();
		try{
			return session.selectList("school.selectSchoolList");
		}finally{
			session.close();
		}
	}
	//학교의 학생수 범위로 조회
	public List<School> selectSchoolByEnrollmentRange(int sNum, int eNum){
		SqlSession session = factory.openSession();
		
		HashMap<String, Integer> map = new HashMap<>();
		map.put("a", sNum);
		map.put("b", eNum);
		   
		try{
			return session.selectList("school.selectRange", map);
		}finally{
			session.close();
		}
	}
	//학교 주소로 조회 - 부분일치 (like)
	public List<School> selectSchoolByAddress(String schoolAddress){
		SqlSession session = factory.openSession();
		try{
			return session.selectList("school.selectSchoolByAddress", schoolAddress);
		}finally{
			session.close();
		}
	}
	
}
